package cn.ixinjiu.libraryMangement.dao.impl;

import cn.ixinjiu.libraryMangement.dao.IAnnoDao;
import cn.ixinjiu.libraryMangement.entity.Anno;
import cn.ixinjiu.libraryMangement.utils.JDBCUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by XinChen on 2023-06-11
 *
 * @TODO
 */
public class AnnoDaoImpl implements IAnnoDao {
    @Override
    public List<Anno> annos() {
        try {
            ResultSet query = JDBCUtil.query("select * from announcement;", null);
            List<Anno> annoList = new ArrayList<>();
            while (query.next()) {
                int id = query.getInt("id");
                String content = query.getString("content");
                Anno anno = new Anno(id, content);
                annoList.add(anno);
            }
            return annoList;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int count() {
        try {
            ResultSet query = JDBCUtil.query("SELECT COUNT(*) as count FROM `announcement`", null);
            while (query.next()) {
                return query.getInt("count");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return 0;
    }

    @Override
    public Anno getAnnoById(int bid) {
        try {
            ResultSet query = JDBCUtil.query("select * from announcement where id = ?", new Object[]{bid});
            while (query.next()) {
                int id = query.getInt("id");
                String content = query.getString("content");
                return new Anno(id, content);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public int annoAdd(Anno anno) {
        return JDBCUtil.update("INSERT INTO `announcement` VALUES (null, ?);", new Object[]{anno.getContent()});
    }

    @Override
    public int annoUpd(Anno anno) {
        return JDBCUtil.update("UPDATE `announcement` SET `content` = ? WHERE `id` = ?;", new Object[]{anno.getContent(), anno.getId()});
    }

    @Override
    public int annoDel(int id) {
        return JDBCUtil.update("delete from announcement where id = ?", new Object[]{id});
    }
}
